package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWxMapper;
import cn.stylefeng.guns.sys.modular.system.service.LoginService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Service
public class LoginServiceImpl implements LoginService {

    private static Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    public static final String APPID = "wx373650bf8de7f27d";//正式
//    public static final String APPID = "wx0215c6330cc918bf";//测试
    public static final String APPSECRET = "d3e9c259a6dbca1c5ef73beb1804f3c7";//正式
//    public static final String APPSECRET = "0fcde62d6cb354aad9f36b17520e8d87";//测试
    @Resource
    private BtyWxMapper wxMapper;
    @Resource
    private GzhConfig gzhConfig;


    /**
     * 获取微信openID,tocken
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public Map get(String code) throws ServletException, IOException {

        //第二步：通过code换取网页授权access_token

        //从request里面获取code参数(当微信服务器访问回调地址的时候，会把code参数传递过来)
//        String code = request.getParameter("code");

        System.out.println("code:" + code);

        logger.info(code+ "\\\\\\\\\\\\");

        //获取code后，请求以下链接获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + gzhConfig.getAppid()
                + "&secret=" + gzhConfig.getSecret()
                + "&code=" + code
                + "&grant_type=authorization_code";

        //通过网络请求方法来请求上面这个接口
        JSONObject jsonObject = doGetJson(url);

        System.out.println("==========================jsonObject" + jsonObject);

        //从返回的JSON数据中取出access_token和openid，拉取用户信息时用
        String openid = jsonObject.getString("openid");

        logger.info(openid+ "========");

        //根据openid查询该用户是否存在
        Map map = wxMapper.getUserId(openid);
//        map.put("code",code);
        if (ToolUtil.isEmpty(map)){
            map = new HashMap();
            if (ToolUtil.isNotEmpty(openid)){
                map.put("openid",openid);
            }
        }
        map.put("token",code);
//        return openid;

        logger.info(map+"[[[[[[[[[");
        return map;
    }



    public Map getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //第二步：通过code换取网页授权access_token

        //从request里面获取code参数(当微信服务器访问回调地址的时候，会把code参数传递过来)
        String code = request.getParameter("code");

        System.out.println("code:" + code);

        Map map = new HashMap<>();
        //营运总监
        if (code.equals("1")){
            map.put("openid", "oM18PwcvHfPO-c6wFNVSpd2eV6G8");
        }

        return map;
    }




    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        //首先初始化HttpClient对象
        DefaultHttpClient client = new DefaultHttpClient();
        //通过get方式进行提交
        HttpGet httpGet = new HttpGet(url);
        //通过HTTPclient的execute方法进行发送请求
        HttpResponse response = client.execute(httpGet);
        //从response里面拿自己想要的结果
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }
        //把链接释放掉
        httpGet.releaseConnection();
        return jsonObject;
    }

}
